<!-- @author: Fengli -->
<!-- @date: 4/17/19 -->
<!-- @desc: 登陆组件-->
<template>
  <div>
    <form novalidate class="md-layout" @submit.prevent="validateUser">
      <md-card class="md-layout-item md-size-50 md-small-size-100">
        <md-card-header>
          <div class="md-title">Login</div>
        </md-card-header>

        <md-card-content>
          <md-field :class="getValidationClass('email')">
            <label for="email">Email</label>
            <md-input type="email" name="email" id="email" autocomplete="email" v-model="form.email"
                      :disabled="sending"/>
            <span class="md-error" v-if="!$v.form.email.required">请输入邮箱</span>
            <span class="md-error" v-else-if="!$v.form.email.email">无效邮箱</span>
          </md-field>

          <md-field :class="getValidationClass('password')">
            <label for="password">Password</label>
            <md-input type="password" name="password" id="password" v-model="form.password" :disabled="sending"/>
            <span class="md-error" v-if="!$v.form.password.required">请输入密码</span>
            <span class="md-error" v-else-if="!$v.form.password.minLength">密码长度小于6位</span>
            <span class="md-error" v-else-if="!$v.form.password.maxLength">密码长度大于21位</span>
          </md-field>
        </md-card-content>

        <md-progress-bar md-mode="indeterminate" v-if="sending"/>

        <md-card-expand>
          <md-card-actions md-alignment="right">
            <md-button :to="{name:'signUp'}">注册</md-button>
            <md-button type="submit" class="md-primary" :disabled="sending">登陆</md-button>
          </md-card-actions>
        </md-card-expand>
      </md-card>

      <md-snackbar :md-active.sync="msg.showMsg" :md-duration="msg.duration" :md-position="msg.position">{{ msg.content }} </md-snackbar>
    </form>
  </div>
</template>

<script>
  import {validationMixin} from 'vuelidate'
  import {
    required,
    email,
    minLength,
    maxLength
  } from 'vuelidate/lib/validators'
  import axios from 'axios/index'
  import {bulkAddTasksFromBackEnd} from '@/util/service/TaskService'
  import {bulkAddWeekSummary} from '@/util/service/WeekSummaryService'

  require('vue-material')

  export default {
    name: 'Login',
    mixins: [validationMixin],
    data: () => ({
      form: {
        email: null,
        password: null
      },
      msg: {/* 用于配置msg */
        showMsg: false,
        content: null,
        duration: 3000,
        position: 'center'
      },
      sending: false // 是否可以输入
    }),
    validations: {
      form: {
        email: {
          required,
          email
        },
        password: {
          required,
          minLength: minLength(6),
          maxLength: maxLength(21)
        }
      }
    },
    methods: {
      getValidationClass (fieldName) {
        const field = this.$v.form[fieldName]

        if (field) {
          return {
            'md-invalid': field.$invalid && field.$dirty
          }
        }
      },
      clearForm () {
        this.$v.$reset()
        this.form.email = null
        this.form.password = null
      },
      /**
       * 用于调用登陆接口
       */
      login () {
        this.sending = true
        /* 访问后台登陆接口,登陆成功之后请求auth接口 */
        let bodyFormData = new FormData()
        bodyFormData.set('email', this.form.email)
        bodyFormData.append('password', this.form.password)
        axios({
          method: 'post',
          url: this.GLOBAL.prefix + '/login',
          data: bodyFormData,
          config: {headers: {'Content-Type': 'multipart/form-data'}}
        }).then((response) => {
          // 打印出返回值
          // 这里需要在localStorage里面存userID
          if (response.data.code === 'SUCCESS') {
            localStorage.setItem('userId', response.data.data)
            this.auth(this.form.email, this.form.password)
            // this.forAo()
          } else {
            /* 提示登陆异常，需要提示框 */
            this.message({content: response.data.msg, position: 'center', showMsg: true})
            this.sending = false
          }
        }
        ).catch((error) => {
          // api接口可能崩了
          console.log(error)
          this.message({content: '登陆接口异常', position: 'center', showMsg: true})
          this.sending = false
          this.clearForm()
        })
      },
      /**
       * 获取token
       * @param username 登陆账号（注意不是授权用的clientId）
       * @param password 登陆密码 (注意不是授权用到secrect)
       */
      auth (username, password) {
        /* 请求/oauth/token */
        let bodyFormData = new FormData()
        bodyFormData.set('scope', 'read')
        bodyFormData.append('grant_type', 'password')
        bodyFormData.append('username', username)
        bodyFormData.append('password', password)
        axios({
          method: 'post',
          url: this.GLOBAL.prefix + '/oauth/token',
          data: bodyFormData,
          config: {headers: {'Content-Type': 'multipart/form-data'}},
          /* 这里是硬编码 */
          auth: {
            username: 'test',
            password: 'test'
          }
        }).then((response) => {
          // 打印出结果
          console.log(response.data)
          /* 存储token,我存在localStorage里面 */
          let token = JSON.stringify(response.data)
          localStorage.setItem('token', token)
          // 这里应该要有一个获取后台所有数据的接口，所以当退出登陆时，一定要保证本地的所有数据都已经同步到远程服务器上，并且将本地数据清除
          this.pullDataFromBackEnd()
        }).catch((error) => {
          console.log(error)
          this.message({content: '获取token接口异常', position: 'center', showMsg: true})
        })
      },
      /**
       * 从后台获取任务，如task，weekSummary
       */
      pullDataFromBackEnd () {
        let token = JSON.parse(localStorage.getItem('token'))
        let userId = localStorage.getItem('userId')
        axios({
          method: 'get',
          url: this.GLOBAL.prefix + '/pullDataFromBackEnd',
          params: {
            userId: userId
          },
          headers: {
            Authorization: token.token_type + ' ' + token.access_token
          }
        }).then((response) => {
          /* 批量写入数据到后台去 */
          bulkAddTasksFromBackEnd(response.data.data[0])
          bulkAddWeekSummary(response.data.data[1])
          // 获取数据成功之后，调整到首页
          this.$router.push({path: '/'})
        }).catch((error) => {
          this.message({content: '获取后台数据接口异常', position: 'center', showMsg: true})
          throw error
        })
      },
      validateUser () {
        this.$v.$touch()

        if (!this.$v.$invalid) {
          this.login()
        }
      },
      /**
       * 用于配置msg,option具体配置减data部分的msg
       * @param option
       */
      message (option) {
        this.msg = option
      },
      forAo () {
        let bodyFormData = new FormData()
        bodyFormData.set('__VIEWSTATE', 'XzK1feQB4bX4fJ9jz2CPOSXbnAoHhLd/qKdAV0SD0JytJc2LkjDE3YpWMSBUsJWrBJadAXha1/gcnlwmp1Bz/L/GeoIUGFoPlMbkZWko1+u5J++8vl/MZY6Ah/tSaHXjLElAh9XQxQnHWzGFfYDPftLhjP8qK7v9R2P9zgBCsww3wh+0YFsLQzUZsqQQC0mfmwkz1hTzqZULGTlA8D4wJQgEfNrrtp9Ifxxy9ccxzhvH4IjnBkvME4ZvZ3kKkPHUIC1TZ+fN23AsHOyx8Y7zFcVAAQIIUF2JRViKis3GTu2nvlRNqmWYC6nUUZ0qFC+iWkKjFXvCrIkDEieletvQlPxBmrOPhh9hjVcLg29qT2XErmThthb9PxIsI1ndr6gV+2Q0VqyBTlpAlU6Zwm9KlC3WbKjLI7guWo3F5Qntk6dYs8gls5wkbTvE2bJmEBwaVPJ/oRqyVqGwkzjKHzPPwg==')
        bodyFormData.append('__EVENTVALIDATION', 'ptbiFu0IXjOLwVemz8jeLb+qs6nd4YYBNZXbApXQxic8PmFTOKK5AbHU6IYGNNp/d1rCvwm5yuVkH3agYUIAXIc1DtZNtsfD')
        bodyFormData.append('txt_User', '201513040412')
        bodyFormData.append('txt_Pwd', 'duanao123')
        bodyFormData.append('HidPassword', '')
        bodyFormData.append('txt_Code', '')
        bodyFormData.append('btnLogin', '')
        axios.post({
          method: 'post',
          url: 'http://localhost/OnlinePay/Login.aspx',
          data: bodyFormData,
          config: {headers: {'Content-Type': 'multipart/form-data'}}
        }).then((response) => {
          console.log(response.data)
        }).catch((error) => {
          console.log(error)
        })
      }
    }
  }
</script>

<style scoped>

</style>
